package com.vibeplayer.app.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.vibeplayer.app.R;
import com.vibeplayer.app.model.Song;
import com.vibeplayer.app.util.MediaScanner;

import java.util.List;

public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongViewHolder> {

    private Context context;
    private List<Song> songs;
    private SongClickListener listener;
    private MediaScanner mediaScanner;

    public SongAdapter(Context context, List<Song> songs, SongClickListener listener) {
        this.context = context;
        this.songs = songs;
        this.listener = listener;
        this.mediaScanner = new MediaScanner(context);
    }

    @NonNull
    @Override
    public SongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_song, parent, false);
        return new SongViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SongViewHolder holder, int position) {
        Song song = songs.get(position);
        holder.txtTitle.setText(song.getTitle());
        holder.txtArtist.setText(song.getArtist());
        holder.txtDuration.setText(song.getDurationString());
        
        // 加载专辑封面
        Uri albumArtUri = mediaScanner.getAlbumArtUri(song.getAlbumId());
        try {
            holder.imgAlbumArt.setImageURI(albumArtUri);
            if (holder.imgAlbumArt.getDrawable() == null) {
                holder.imgAlbumArt.setImageResource(R.drawable.default_album_art);
            }
        } catch (Exception e) {
            holder.imgAlbumArt.setImageResource(R.drawable.default_album_art);
        }
    }

    @Override
    public int getItemCount() {
        return songs.size();
    }

    public class SongViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView imgAlbumArt;
        TextView txtTitle;
        TextView txtArtist;
        TextView txtDuration;

        public SongViewHolder(@NonNull View itemView) {
            super(itemView);
            imgAlbumArt = itemView.findViewById(R.id.imgAlbumArt);
            txtTitle = itemView.findViewById(R.id.txtTitle);
            txtArtist = itemView.findViewById(R.id.txtArtist);
            txtDuration = itemView.findViewById(R.id.txtDuration);
            
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onSongClick(getAdapterPosition());
            }
        }
    }

    public interface SongClickListener {
        void onSongClick(int position);
    }
} 